package com.leetcode.partition6;

import java.util.Arrays;
import java.util.Stack;

/**
 * @author `RKC`
 * @date 2021/10/7 10:28
 */
public class LC503下一个更大元素2 {

    public static int[] nextGreaterElements(int[] nums) {
        return monotonicStack(nums);
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 1};
        System.out.println(Arrays.toString(nextGreaterElements(nums)));
    }

    private static int[] monotonicStack(int[] nums) {
        //将nums扩容一倍（不需要真扩容，当遍历的下标大于等于nums的长度时，进行取模运算进行虚拟扩容），扩容后的数组拼接在原数组后面
        //按照正常的（非环型）要求完成
        int[] answers = new int[nums.length];
        Stack<Integer> s = new Stack<>();
        s.push(0);
        Arrays.fill(answers, -1);
        for (int i = 1; i < nums.length * 2; i++) {
            int j = i;
            if (i >= nums.length) j %= nums.length;
            if (nums[j] > nums[s.peek()]) {
                while (!s.isEmpty() && nums[s.peek()] < nums[j]) {
                    answers[s.peek()] = nums[j];
                    s.pop();
                }
            }
            s.push(j);
        }
        return answers;
    }
}
